﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Infinity.Expressions.Extension;
using Infinity.Expressions.Core;

namespace Infinity.Expressions.Conditions
{
	/// <summary>
	/// If-Then-Else elágazás implementációja
	/// </summary>
	public class IfStatement : Condition
	{
		/// <summary>
		/// Az elágazás feltétele
		/// </summary>
		public Expression Condition { get; set; }
		/// <summary>
		/// Ez a program fut le ha False értékelődik ki. 
		/// </summary>
		public AbstractProgram FalseBlock { get; set; }
		/// <summary>
		/// Ez a program fut le ha True értékelődik ki. 
		/// </summary>
		public AbstractProgram TrueBlock { get; set; }

		public override void Run()
		{
			if (Condition != null)
			{
				if (Condition.CompileExpression<Func<bool>>()())
				{
					if (TrueBlock != null)
					{
						TrueBlock.Run();
					}
				}
				else
				{
					if (FalseBlock != null)
					{
						FalseBlock.Run();
					}
				}
			}
		}

		protected override Expression BodyExpression
		{
			get
			{
				if (TrueBlock != null || FalseBlock != null)
				{
					if (FalseBlock != null)
					{
						return Expression.IfThenElse(Condition, TrueBlock.ToExpression(), FalseBlock.ToExpression());
					}
					else
					{
						return Expression.IfThen(Condition, TrueBlock.ToExpression());
					}
				}
				else
				{
					return null;
				}
			}
		}
	}
}
